"""
用于操作配置文件
"""
from os.path import join, dirname, abspath
import configparser

BASE_PATH = dirname(dirname(abspath(__file__)))
CONFIG_PATH = join(BASE_PATH, 'config')


class Config:
    def __init__(self, filename):
        """filename的值就是配置文件的名字"""
        self.filename = filename
        # 实例化ConfigParser对象
        self.cf = configparser.ConfigParser()
        self.cf.optionxform = str  # 键不转换成小写
        self.cf.read(join(CONFIG_PATH, filename))

    def add_config(self, section, option, value):
        self.cf.set(section, option, value)
        with open(join(CONFIG_PATH, self.filename), 'w') as f:
            self.cf.write(f)

    # 读取配置文件
    def read_config(self, section, option):
        """section是扇区名，option是变量名"""
        return self.cf.get(section, option)

    # 读取扇区
    def read_section(self, section):
        """返回扇区里面的键值对组成的字典"""
        dct = {}
        for key, raw in self.cf.items(section):
            # 处理所有内容统统识别成字符串的问题
            try:
                dct[key] = self.cf.getboolean(section, key)
            except ValueError:
                try:
                    dct[key] = self.cf.getint(section, key)
                except ValueError:
                    dct[key] = raw
        return dct

    # 读取capabilities
    def read_capabilities(self, app_name):
        """根据app_name组装完整的capabilities并返回"""
        # 读取 capabilities 扇区的内容
        cap_dict = self.read_section("capabilities")
        # 读取 app_name 扇区的内容
        app_dict = self.read_section(app_name)
        # 装成字典
        cap_dict.update(app_dict)
        return cap_dict


if __name__ == '__main__':
    c = Config("app.ini")
    print(c.read_capabilities('xiachufang'))
